package cn.gok.utils;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @author: DxlinY
 * @apiNote: 对象工具类
 * @date: 2020/11/5
 * @time: 16:05
 */
public class BeanUtil {

    /**
     * 对象变map
     *
     * @param clazz  类对象
     * @param target 目标对象
     * @return map
     */
    public static Map <String, Object> objectToMap(Class clazz, Object target) {
        Field[] fields = clazz.getDeclaredFields();
        Method[] methods = clazz.getMethods();
        Map <String, Object> result = new HashMap <>();
        for (Field field : fields) {
            String getName = ("get" + field.getName()).toLowerCase();
            for (Method m : methods) {
                if (m.getName().toLowerCase().equals(getName)) {
                    try {
                        Object value = m.invoke(target);
                        TableId tableId = field.getAnnotation(TableId.class);
                        TableField tableField = field.getAnnotation(TableField.class);
                        Optional.ofNullable(value).ifPresent(f -> result.put(tableId == null ? tableField.value() : tableId.value(), value));
                    } catch (IllegalAccessException | InvocationTargetException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return result;
    }


}
